#!/bin/sh

## This script is a cron wrapper for cyrptshotr.
# It was made to help ensure backup run, even if the lid was closed when
# they should have. It will default to running the periodicity if not found
# in the log. There is some buffer time built in, to avoid dropping backups.
# It will delete old periodicity log entires on pass.


## Set log location.
CONF_DIR="$HOME/.config/cryptshotr-cron"
LOG_PATH="$CONF_DIR/log"

## Get start time, in epoch
start=$(date +%s)

## Test for conf dir, make if missing
if [ ! -d $CONF_DIR ]; then
	mkdir -p $CONF_DIR
fi

### Set Time Check ### {{{
## Declare intended interval distance in seconds
# hour 3600, day 86400, week 604800, month 2419200, year 29030400
s_hour=3600
s_day=86400
s_week=604800
s_month=2419200
s_year=29030400

## Added a buffer, to help reduce dropping backup frequency
b_hour=0		# Zero Hours
b_day=14400		# Four hours
b_week=14400	# Four hours
b_month=14400	# Four hours
b_year=14400	# Four hours

## Initialize values to beat, add one for postarity
# buffer margin: hourly 0, daily 4h, weekly 4h, monthly 6h, year 12h
ch_hour=$(($start + 1 - $s_hour + $b_hour))
ch_day=$(($start + 1 - $s_day + $b_day))
ch_week=$(($start + 1 - $s_week + $b_week))
ch_month=$(($start + 1 - $s_month + $b_month))
ch_year=$(($start + 1 - $s_year + $b_year))
### End Set Time Check ### }}}

### Last Run Check ### {{{
## Initialize last run for periodicity to being un-run
lr_hour=0
lr_day=0
lr_week=0
lr_month=0
lr_year=0

if [ -e $LOG_PATH ]; then
	## Awk matches one periodicity, and sees if last instance passed.
	## If passed, set var to when. Otherwise set to un-run.
	lr_hour=$(awk '/hourly/ {LL=$0} END {match(LL, /(\w+)\t(passed)\t([0-9]+)/, m); if(m[3]==""){print 0} else {print m[3]}}' $LOG_PATH)
	lr_day=$(awk '/daily/ {LL=$0} END {match(LL, /(\w+)\t(passed)\t([0-9]+)/, m); if(m[3]==""){print 0} else {print m[3]}}' $LOG_PATH)
	lr_week=$(awk '/weekly/ {LL=$0} END {match(LL, /(\w+)\t(passed)\t([0-9]+)/, m); if(m[3]==""){print 0} else {print m[3]}}' $LOG_PATH)
	lr_month=$(awk '/monthly/ {LL=$0} END {match(LL, /(\w+)\t(passed)\t([0-9]+)/, m); if(m[3]==""){print 0} else {print m[3]}}' $LOG_PATH)
	lr_year=$(awk '/yearly/ {LL=$0} END {match(LL, /(\w+)\t(passed)\t([0-9]+)/, m); if(m[3]==""){print 0} else {print m[3]}}' $LOG_PATH)
fi
### End Last Run Check ### }}}

### Backup Check and Run ### {{{
backup_ch() {
	if [ $2 -lt $3 ]; then
		## Run backup periodicity
		sudo /usr/local/sbin/cryptshotr -q $4

		if [ $? -eq 0 ]; then
			## Purge old periodicity entries if passed
			sed -i "/$4/d" $1
			echo "$(date '+%F %T')\t$4\tpassed\t$(date '+%s')" | cat >> $1
		  else
			echo "$(date '+%F %T')\t$4\tFAILED\t$(date '+%s')" | cat >> $1
		fi
	fi
}

backup_ch $LOG_PATH $lr_hour $ch_hour "hourly"
backup_ch $LOG_PATH $lr_day $ch_day "daily"
backup_ch $LOG_PATH $lr_week $ch_week "weekly"
backup_ch $LOG_PATH $lr_month $ch_month "monthly"
backup_ch $LOG_PATH $lr_year $ch_year "yearly"
### End Backup Check and Run ### }}}
